package com.shanghaionstar.smart.zxing;

import android.app.Activity;
import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.Vibrator;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.Result;
import com.onstar.cn.common.exception.OnStarException;
import com.onstar.cn.framework.mvp.base.core.BaseActivity;
import com.onstar.cn.framework.mvp.base.core.BasePresenter;
import com.onstar.cn.smart.BaseResponse;
import com.onstar.cn.weight.ProgressLayout;
import com.onstar.cn.weight.ToastView;
import com.shanghaionstar.R;
import com.shanghaionstar.enumtype.FunctionNameFindId;
import com.shanghaionstar.smart.SmartHomeActivity;
import com.shanghaionstar.smart.iview.ISmartCaptureView;
import com.shanghaionstar.smart.presenter.SmartCapturePresenter;
import com.shanghaionstar.smart.zxing.camera.CameraManager;
import com.shanghaionstar.smart.zxing.decoding.CaptureActivityHandler;
import com.shanghaionstar.smart.zxing.decoding.InactivityTimer;
import com.shanghaionstar.smart.zxing.view.ViewfinderView;
import com.shanghaionstar.utils.BusinessUtil;

import java.io.IOException;
import java.util.Vector;


/**
 * Initial the camera
 * 
 * @author Ryan.Tang
 */
public class MipcaActivityCapture  extends BaseActivity implements SurfaceHolder.Callback,View.OnClickListener, ISmartCaptureView  {
	private CaptureActivityHandler handler;
	private ViewfinderView viewfinderView;
	private boolean hasSurface;
	private Vector<BarcodeFormat> decodeFormats;
	private String characterSet;
	private InactivityTimer inactivityTimer;
	private MediaPlayer mediaPlayer;
	private boolean playBeep;
	private static final float BEEP_VOLUME = 0.10f;
	private boolean vibrate;

	private TextView mTitleTv;
	private TextView mSmartTv;
	private TextView mScanTv;
	private ProgressLayout mProgressLayout;
	private SmartCapturePresenter presenter;
	private boolean from;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_capture);
		BusinessUtil.sendReportByClickType(this, FunctionNameFindId.Mobile_ScanBarCode.getStringValue());

		// ViewUtil.addTopView(getApplicationContext(), this,
		// R.string.scan_card);
		presenter = new SmartCapturePresenter(getScheduler());
		presenter.setView(this);
		initView();
		CameraManager.init(getApplication());
		viewfinderView = (ViewfinderView) findViewById(R.id.viewfinder_view);
		viewfinderView.post(new Runnable() {
			@Override
			public void run() {
				if (!from) {
					Rect rect = CameraManager.get().getFramingRect();
					RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) mScanTv.getLayoutParams();
					params.setMargins(0, rect.bottom, 0, 0);
					mScanTv.setLayoutParams(params);
				}
			}
		});
		hasSurface = false;
		inactivityTimer = new InactivityTimer(this);
	}

	private void initView() {
		Intent it = getIntent();
		mTitleTv = (TextView) findViewById(R.id.title_tv);
		mProgressLayout = (ProgressLayout) findViewById(R.id.progress_layout);
		findViewById(R.id.back_ib).setOnClickListener(this);
		mSmartTv = (TextView) findViewById(R.id.smart_tip_tv);
		mScanTv = (TextView) findViewById(R.id.scan_tip_tv);
		from = it != null && it.getIntExtra("requestCode", -1) == SmartHomeActivity.REQUEST_CODE;
		switchTips(from);
	}

	private void switchTips(boolean fromSmart) {
		if (fromSmart) {
			mSmartTv.setVisibility(View.VISIBLE);
			mScanTv.setVisibility(View.GONE);
			mTitleTv.setText(R.string.smart_add_device);
		} else {
			mSmartTv.setVisibility(View.GONE);
			mScanTv.setVisibility(View.VISIBLE);
			mTitleTv.setText(R.string.scan_title);
		}
	}

	@Override
	public BasePresenter getPresenter() {
		return presenter;
	}

	@Override
	protected void onResume() {
		super.onResume();
		SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
		SurfaceHolder surfaceHolder = surfaceView.getHolder();
		if (hasSurface) {
			initCamera(surfaceHolder);
		} else {
			surfaceHolder.addCallback(this);
			surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
		}
		decodeFormats = null;
		characterSet = null;

		playBeep = true;
		AudioManager audioService = (AudioManager) getSystemService(AUDIO_SERVICE);
		if (audioService.getRingerMode() != AudioManager.RINGER_MODE_NORMAL) {
			playBeep = false;
		}
		initBeepSound();
		vibrate = true;

	}

	@Override
	protected void onPause() {
		super.onPause();
		if (handler != null) {
			handler.quitSynchronously();
			handler = null;
		}
		CameraManager.get().closeDriver();
	}

	@Override
	protected void onDestroy() {
		inactivityTimer.shutdown();
		super.onDestroy();
	}

	/**
	 * ����ɨ����
	 * 
	 * @param result
	 * @param barcode
	 */
	public void handleDecode(Result result, Bitmap barcode) {
		inactivityTimer.onActivity();
		playBeepSoundAndVibrate();

		String resultString = result.getText();
		if (resultString.equals("")) {
			Toast.makeText(MipcaActivityCapture.this, "Scan failed!", Toast.LENGTH_SHORT).show();
			finish();
		} else {
			if (from) {
				Intent intent = new Intent();
				intent.setClass(this, SmartHomeActivity.class);
				intent.putExtra("result",resultString);
				setResult(RESULT_OK, intent);
				finish();
			} else {
				presenter.authQRcode(resultString);
			}

//			Intent resultIntent = new Intent();
//			Bundle bundle = new Bundle();
//			bundle.putString("result", resultString);
////			bundle.putParcelable("bitmap", barcode);
//			resultIntent.putExtras(bundle);
//			this.setResult(RESULT_OK, resultIntent);
		}

	}

	private void initCamera(SurfaceHolder surfaceHolder) {
		try {
			CameraManager.get().openDriver(surfaceHolder);
		} catch (IOException ioe) {
			return;
		} catch (RuntimeException e) {
			return;
		}
		if (handler == null) {
			handler = new CaptureActivityHandler(this, decodeFormats, characterSet);
		}
	}

	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

	}

	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		if (!hasSurface) {
			hasSurface = true;
			initCamera(holder);
		}

	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		hasSurface = false;
	}

	public ViewfinderView getViewfinderView() {
		return viewfinderView;
	}

	public Handler getHandler() {
		return handler;
	}

	public void drawViewfinder() {
		viewfinderView.drawViewfinder();
	}

	private void initBeepSound() {
		if (playBeep && mediaPlayer == null) {
			// The volume on STREAM_SYSTEM is not adjustable, and users found it
			// too loud,
			// so we now play on the music stream.
			setVolumeControlStream(AudioManager.STREAM_MUSIC);
			mediaPlayer = new MediaPlayer();
			mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
			mediaPlayer.setOnCompletionListener(beepListener);

			AssetFileDescriptor file = getResources().openRawResourceFd(R.raw.beep);
			try {
				mediaPlayer.setDataSource(file.getFileDescriptor(), file.getStartOffset(), file.getLength());
				file.close();
				mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
				mediaPlayer.prepare();
			} catch (IOException e) {
				mediaPlayer = null;
			}
		}
	}

	private static final long VIBRATE_DURATION = 200L;

	private void playBeepSoundAndVibrate() {
		if (playBeep && mediaPlayer != null) {
			mediaPlayer.start();
		}
		if (vibrate) {
			Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
			vibrator.vibrate(VIBRATE_DURATION);
		}
	}

	/**
	 * When the beep has finished playing, rewind to queue up another one.
	 */
	private final OnCompletionListener beepListener = new OnCompletionListener() {
		public void onCompletion(MediaPlayer mediaPlayer) {
			mediaPlayer.seekTo(0);
		}
	};

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
			case R.id.back_ib:
				BusinessUtil.sendReportByClickType(this, FunctionNameFindId.Smarthome_scanQRcode_return.getStringValue());
				this.finish();
				break;
		}
	}

	@Override
	public void setLoading(boolean isLoading) {
		mProgressLayout.setVisibility(isLoading ? View.VISIBLE : View.GONE);
	}

	@Override
	public void onResponseError(OnStarException e) {
		new ToastView(this).showToast(R.string.scan_verify_failed);
		finish();
	}

	@Override
	public void onReponseSuccess(Object object) {
		if (object instanceof BaseResponse) {
			if (object!= null && ((BaseResponse) object).code.equalsIgnoreCase("E0000")) {
				new ToastView(this).showToast(R.string.scan_verify_success);
				finish();
			} else {
				new ToastView(this).showToast(R.string.scan_verify_failed);
				finish();
			}
		}
	}

	@Override
	public Activity onActivity() {
		return this;
	}
}